package com.tanhua.dubbo.utils;

import com.itheima.model.mongo.Sequence;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class IdWork {
    @Autowired
    private MongoTemplate mongoTemplate;

    public Long getNextId(String collName){
        Query query = new Query(Criteria.where("collName").is(collName));

        Update update = new Update();
        update.inc("seqId", 1);

        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);

        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }
    @Before("execution(* org.springframework.cloud.client.serviceregistry.ServiceRegistry.register(*)) && args(registration)")
    public void beforeRegister(Registration registration) {
        DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance();
        dubboBootstrap.start();
    }
}
